package com.spzx.product.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.github.pagehelper.PageHelper;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.core.web.page.TableDataInfo;
import com.spzx.product.api.domain.ProductSkuVo;
import com.spzx.product.api.domain.SkuPriceVo;
import com.spzx.product.domain.Product;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.query.SkuQuery;
import com.spzx.product.service.*;
import com.spzx.product.vo.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@Tag(name = "聚合数据")
@RestController
@RequestMapping("/channel")
public class ChannelController extends BaseController {
    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private IProductSkuService productSkuService;

    @Autowired
    private IBrandService brandService;

    @Autowired
    private IProductService productService;

    @Autowired
    private ISkuStockService skuStockService;

    @Autowired
    private IProductDetailsService productDetailsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;


    @Operation(summary = "获取首页数据")
    @GetMapping("/index")
    public AjaxResult index() {
        // 获取一级分类数据
        List<CategoryVo> levelOneCategory = categoryService.getLevelOneCategory();
        // 获取商品数据
        List<ProductSkuVo> productSkuVoList = productSkuService.getProductSkuVoList();
        //封装到IndexDataVo中
        return AjaxResult.success(new IndexDataVo(levelOneCategory, productSkuVoList));
    }

    @Operation(summary = "获取分类嵌套列表")
    @GetMapping("/category")
    public AjaxResult category() {
        return AjaxResult.success(categoryService.tree());
    }

    @Operation(summary = "显示商品列表")
    @GetMapping("/skuList/{pageNum}/{pageSize}")
    public TableDataInfo skuList(
            @Parameter(description = "当前页码")
            @PathVariable Integer pageNum,

            @Parameter(description = "每页记录数")
            @PathVariable Integer pageSize,

            SkuQuery skuQuery) {
        PageHelper.startPage(pageNum, pageSize);
        List<ProductSkuVo> productSkuVoList = productSkuService.selectProductSkuVoList(skuQuery);
        return getDataTable(productSkuVoList);
    }

    @Operation(summary = "获取全部品牌")
    @GetMapping("/brand")
    public AjaxResult selectBrandAll() {
        return AjaxResult.success(brandService.list());
    }

    @Operation(summary = "商品详情")
    @GetMapping("/item/{skuId}")
    public AjaxResult item(
            @Parameter(description = "skuId")
            @PathVariable Long skuId) {
        ItemVo itemVo = new ItemVo();
        // 查询Sku信息
        String key = "product:sku:data";
        Boolean flag = redisTemplate.opsForValue().getBit(key, skuId);
        if (!flag) {
            //查询数据不存在直接返回空对象
            throw new ServiceException("用户查询商品sku不存在");
        }

        CompletableFuture<Long> skuFuture = CompletableFuture.supplyAsync(() -> {
            ProductSku productSku = productSkuService.getProductSku(skuId);
            itemVo.setProductSku(productSku);
            return productSku.getProductId();
        }, threadPoolExecutor);
        CompletableFuture<Void> skuStockFuture = CompletableFuture.runAsync(() -> {
            // 根据skuId查询库存
            SkuStockVo skuStock = skuStockService.getSkuStock(skuId);
            itemVo.setSkuStock(skuStock);
        }, threadPoolExecutor);
        CompletableFuture<Void> productFuture = skuFuture.thenAcceptAsync(productId -> {
            // 商品信息
            Product product = productService.getById(productId);
            // 查询轮播图
            String[] sliderUrlList = product.getSliderUrls().split(",");
            itemVo.setSliderUrlList(sliderUrlList);
            // 查询商品规格对应商品skuId信息
            JSONArray specValueList = JSON.parseArray(product.getSpecValue());
            itemVo.setSpecValueList(specValueList);
        }, threadPoolExecutor);
        CompletableFuture<Void> detailsFuture = skuFuture.thenAcceptAsync(productId -> {
            // 查询商品详细图片
            String[] detailsImageUrlList = productDetailsService.getProductDetails(productId);
            itemVo.setDetailsImageUrlList(detailsImageUrlList);
        }, threadPoolExecutor);
        CompletableFuture<Void> specMapFuture = CompletableFuture.runAsync(() -> {
            // 查询商品规格信息
            Map<String, Long> skuSpecValueList = productSkuService.getSkuSpecValue(skuId);
            itemVo.setSkuSpecValueMap(skuSpecValueList);
        }, threadPoolExecutor);
        CompletableFuture<Void> priceFuture = CompletableFuture.runAsync(() -> {
            // 查询最新价格信息
            SkuPriceVo skuPrice = productSkuService.getSkuPrice(skuId);
            itemVo.setSkuPrice(skuPrice);
        }, threadPoolExecutor);

        // 等待所有任务完成
        CompletableFuture.allOf(skuFuture, skuStockFuture, specMapFuture, priceFuture, productFuture, detailsFuture).join();

        return AjaxResult.success(itemVo);
    }

}
